package com.ruoyi.lvlian.controller;

import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.lvlian.domain.DriverInfo;
import com.ruoyi.lvlian.domain.DriverVehicleRef;
import com.ruoyi.lvlian.domain.InvoiceInfo;
import com.ruoyi.lvlian.domain.VehicleInfo;
import com.ruoyi.lvlian.dto.DriverInfoDto;
import com.ruoyi.lvlian.service.ICommonService;
import com.ruoyi.lvlian.service.IDriverInfoService;
import com.ruoyi.lvlian.vo.DriverInfoVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/driverInfo")
@Api(value = "司机信息Controller", tags = "司机信息Controller")
public class DriverInfoController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(DriverInfoController.class);
    @Autowired
    private IDriverInfoService driverInfoService;


    @Autowired
    private ICommonService iCommonService;

    @ApiOperation("查询司机信息列表")
    @GetMapping("/list")
    public TableDataInfo list(DriverInfoDto driverInfo) {
        startPage();
        if (Objects.isNull(driverInfo.getOrgCodes()) || driverInfo.getOrgCodes().isEmpty()) {
            return null;
        }
        List<DriverInfoVo> list = driverInfoService.selectDriverInfoList(driverInfo);
        return getDataTable(list);
    }


    @ApiOperation("小程序后台司机，事务司机数据")
    @GetMapping("/wechatList")
    public TableDataInfo wechatList(DriverInfoDto driverInfo) {

        startPage();
        List<DriverInfoVo> list = driverInfoService.wechatList(driverInfo);
        return getDataTable(list);
    }

    @ApiOperation("获取司机信息详细信息")
//    //@RequiresPermissions("lvlian:driverInfo:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return success(driverInfoService.selectDriverInfoById(id));
    }


    @ApiOperation("获取司机信息详细信息息getInfoById")
    @GetMapping("/getInfoById")
    public AjaxResult getInfoById(@ApiParam(value = "司机信息详细信息id", required = true) @RequestParam(value = "id") String id) {
        return success(driverInfoService.selectDriverInfoById(id));
    }


    @ApiOperation("新增司机信息")
    @Log(title = "司机信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody DriverInfo driverInfo) {
        log.info(driverInfo.toString());
        if (StringUtils.isEmpty(driverInfo.getPhoneNo())) {
            return error("手机号码不能为空");
        }

        if (StringUtils.isEmpty(driverInfo.getName())) {
            return error("司机姓名不能为空");
        }
        if (StringUtils.isEmpty(driverInfo.getLicenseNo())) {
            return error("驾驶证号不能为空");
        }
        try {
        return toAjax(driverInfoService.insertDriverInfo(driverInfo));
        }catch (Exception e){
            return error("保存失败");
        }
    }

    @ApiOperation("修改司机信息")
//    //@RequiresPermissions("lvlian:driverInfo:edit")
    @Log(title = "司机信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody @Validated DriverInfo driverInfo) {
        log.info(driverInfo.toString());
//        if (StringUtils.isEmpty(driverInfo.getPhoneNo())) {
//            return error("手机号码不能为空");
//        }

        if (StringUtils.isEmpty(driverInfo.getName())) {
            return error("司机姓名不能为空");
        }
        if (StringUtils.isEmpty(driverInfo.getLicenseNo())) {
            return error("驾驶证号不能为空");
        }
        try {
            return toAjax(driverInfoService.updateDriverInfo(driverInfo));
        }catch (Exception e){
            return error("保存失败");
        }


    }


    @ApiOperation("通过手机号码查询司机信息")
    @GetMapping("/getDriverByPhone")
    public AjaxResult getDriverByPhone(@RequestParam @NotBlank(message = "手机号码不能为空") String phone,@RequestParam(defaultValue = "小程序") String dataSource ) {
        boolean validPhoneNumber = StringUtils.isValidPhoneNumber(phone);
        if (validPhoneNumber) {
            DriverInfoVo driver = driverInfoService.getDriverByPhone(phone,dataSource);

            if (driver == null) {
                return error("该司机不存在");
            }
            return success(driver);
        } else {
            return error("号码不对");
        }

    }


    @ApiOperation("通过手机号码查询司机信息")
    @GetMapping("/getDriverBylicenseOrIdcard")
    public AjaxResult getDriverBylicenseOrIdcard(@RequestParam @Validated @NotBlank(message = "驾驶证号码不能为空") String licenseNo) {


        if (StringUtils.isEmpty(licenseNo) || licenseNo.length()<3 ) {
            return error("驾驶证号码为空,驾驶证号码不对");
        }
        boolean validLicenseNumber = true;// IDCardValidator.isValidIDCard(licenseNo);
        if (validLicenseNumber) {

            DriverInfoVo driver = driverInfoService.getDriverBylicenseOrIdcard(licenseNo);

            if (driver == null) {
                return error("该司机不存在");
            }
            return success(driver);
        } else {
            return error("驾驶证号码不对");
        }

    }

    @ApiOperation("通过车牌号码查询司机信息")
    @GetMapping("/getDriverByPlateNo")
    public AjaxResult getDriverByPlateNo(@RequestParam @Validated @NotBlank(message = "车牌号码不能为空") String plateNo) {
        if (StringUtils.isEmpty(plateNo)) {
            return error("车牌号码不能为空");
        }
        DriverInfoVo driver = driverInfoService.getDriverByPlateNo(plateNo);
        if (driver == null) {
            return error("该司机不存在");
        }
        driver.setVehicleInfoList(null);
        driver.setIdCardInfo(null);
        return success(driver);


    }


    @PostMapping("/remove")
    @Log(title = "司机删除", businessType = BusinessType.DELETE)
    public AjaxResult remove(@RequestBody String[] ids) {
        if( ids == null || ids.length == 0  ){
            return error("未选中") ;
        }
        int i = driverInfoService.deleteDriverInfoByIds(ids);
        if(i>0 ){
            return success("删除成功") ;
        }
        return toAjax(i);
    }

    @ApiOperation("导入司机")
    @PostMapping("/importInfo")
    public AjaxResult importInfo(MultipartFile file) {
        // 获取到批量导入的数据集合
        List<DriverInfo> dtoList = null;
        List<DriverInfo> newList = new ArrayList<>();
        try {
            dtoList = driverInfoService.importInfo(file, "司机信息", 3);

            for (DriverInfo po : dtoList) {
                newList.add(po);
            }
            int totalSussess = driverInfoService.bachSave(newList);
            String msg = "解析到" + dtoList.size() + "条数据，" + "导入成功" +  totalSussess + "条，导入失败" + (dtoList.size() - newList.size()) + "条！";
            return success(msg);
        } catch (Exception e) {
            e.printStackTrace();
            if(e.getMessage().contains("Incorrect date")){
                String   message =  e.getMessage();
                String truncatedMessage = message.substring(  message.length() - 140  , message.length() );

                return success("日期填写错误" + truncatedMessage);
            }

            return success("模板数据错误");
        }


    }


    @ApiOperation("司机审批司机信息审批通过")
    @PostMapping("/updateDriver")
    public AjaxResult updateDriver(@RequestBody DriverInfo info) {
        if (StringUtils.isEmpty(info.getId())) {
            return success("id必填");
        }
        return toAjax(driverInfoService.updateDriver(info));
    }

    @ApiOperation("司机绑定解绑车辆")
    @PostMapping("/bind")
    @Log(title = "司机绑定解绑车辆", businessType = BusinessType.UPDATE)
    public AjaxResult bind(@RequestBody DriverVehicleRef info) {
        if (StringUtils.isEmpty(info.getLicenseNo())) {
            return success("驾驶证号必填");
        }
        if (StringUtils.isEmpty(info.getPlateNo())) {
            return success("车牌号必填");
        }
        if (StringUtils.isEmpty(info.getPhone())) {
            return success("手机号必填");
        }
        return toAjax(driverInfoService.bind(info));
    }

    @PostMapping("/deleteBind")
    @Log(title = "删除绑定车辆", businessType = BusinessType.DELETE)
    public AjaxResult deleteBind(@RequestBody DriverVehicleRef info) {
        if(  StringUtils.isEmpty(info.getPlateNo() ) || StringUtils.isEmpty(info.getLicenseNo() )   ){
            return error("未选中") ;
        }
        int i = driverInfoService.deleteBind(info);
        if(i>0 ){
            return success("删除成功") ;
        }
        return toAjax(i);
    }


    @PostMapping("/approve")
    @ApiOperation(" 已通过 已拒绝 待审批")
    @Log(title = "司机审批", businessType = BusinessType.UPDATE)
    public AjaxResult approve( String[] ids , String dataStatus ) {
        if( ids == null || ids.length == 0  ){
            return error("未选中") ;
        }
        int i = driverInfoService.approve(ids ,dataStatus);
        if(i>0 ){
            return success("操作成功") ;
        }
        return toAjax(i);
    }
}
